package com.asset.dispoal.user.service.commom;

import com.asset.dispoal.commom.utils.AES;
import com.asset.dispoal.commom.utils.MD5;
import com.asset.dispoal.user.domain.db.entity.SysUserDo;
import com.asset.dispoal.user.domain.db.mapper.SysUserMapper;
import com.asset.dispoal.user.domain.redis.commom.UserLoginSaveCommand;
import com.asset.dispoal.user.domain.redis.entity.UserRedis;
import com.asset.dispoal.user.dto.UserRequest;
import com.asset.dispoal.user.dto.UserResponse;
import com.asset.dispoal.user.service.converter.UserConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.dict.BasicDict;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.core.sugar.Attempt;
import tech.mhuang.pacebox.core.util.ObjectUtil;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.jwt.admin.JwtFramework;
import tech.mhuang.pacebox.jwt.admin.external.IJwtProducer;
import tech.mhuang.pacebox.springboot.protocol.Result;


/**
 * @author qr
 * @date 2022/1/24$
 */
@Component
public class LoginCommand implements BaseCommand<UserRequest, Result<UserResponse>> {

    @Autowired
    SysUserMapper sysUserMapper;


    @Autowired
    private JwtFramework jwtFramework;

    @Value("${pacebox.filter.filter-def-auth-type}")
    private String authType;

    @Autowired
    UserLoginSaveCommand userLoginSaveCommand;

    @Override
    public Result<UserResponse> execute(UserRequest userRequest) {
        final UserRedis userByAccount = userLoginSaveCommand.getUserByAccount(userRequest.getAccount() + "_" + userRequest.getType());
        if (userByAccount != null) {
            String salt = userRequest.getAccount().substring(userRequest.getAccount().length() - 2);
            String password = Attempt.supply(() -> MD5.getMd5Code(AES.encrypt(salt, userRequest.getPassword()), 1)).get();
            if (password.equals(userRequest.getPassword())) {
                final UserResponse userResponse = UserConverter.INSTANCE.doToRes(userByAccount);
                if (StringUtil.equals(userResponse.getType(), userRequest.getType())) {
                    return Result.ok(userResponse);
                } else {
                    throw new BusinessException(Result.SYS_FAILD, "用户类型不符");
                }

            }
        }

        final Result verify = this.verify(userRequest);
        if (verify != null && verify.getCode() == 500) {
            return verify;
        }
        SysUserDo sysUserDo = (SysUserDo) verify.getData();
        BasicDict claimMap = new BasicDict(4).set("userId", sysUserDo.getId())
                .set("companyType", sysUserDo.getCompanyType())
                .set("companyId", sysUserDo.getCompanyId());
        IJwtProducer jwtProducer = jwtFramework.getProducer(authType);
        String token = jwtProducer.create(claimMap);
        UserRedis redis = new UserRedis();
        redis.setId(sysUserDo.getId());
        redis.setNickname(sysUserDo.getNickname());
        redis.setCompanyId(sysUserDo.getCompanyId());
        redis.setCompanyType(sysUserDo.getCompanyType());
        redis.setAccount(sysUserDo.getAccount());
        redis.setAuthType(authType);
        redis.setType(sysUserDo.getType());
        redis.setRoleIds(sysUserDo.getRoleIds());
        redis.setDepartment(sysUserDo.getDepartmentId());
        redis.setToken(token);
        redis.setHeaderToken(jwtProducer.jwt().getHeaderName());
        userLoginSaveCommand.setUser(redis);
        final UserResponse userResponse = UserConverter.INSTANCE.doToRes(redis);
        userResponse.setLogo(sysUserDo.getLogo());
        if (StringUtil.equals(userResponse.getType(), userRequest.getType())) {
            return Result.ok(userResponse);
        } else {
            throw new BusinessException(Result.SYS_FAILD, "用户类型不符");
        }
    }


    //验证
    private Result verify(UserRequest userRequest) {
        if (ObjectUtil.isEmpty(userRequest) || StringUtil.isBlank(userRequest.getAccount())) {
            throw new BusinessException("参数错误");
        }
        final SysUserDo sysUserDo = sysUserMapper.loginByAccount(userRequest.getAccount(), userRequest.getType());
        if (sysUserDo == null) {
            return Result.faild("账号或者密码错误");
        }
        String salt = userRequest.getAccount().substring(userRequest.getAccount().length() - 2);
        String password = Attempt.supply(() -> MD5.getMd5Code(AES.encrypt(salt, userRequest.getPassword()), 1)).get();
        if (!StringUtil.equals(password, sysUserDo.getPassword())) {
            return Result.faild("账号或者密码错误");
        }
        if ("0".equals(sysUserDo.getState())) {
            return Result.faild("账号已停用");
        }
        return Result.ok(sysUserDo);
    }
}
